package cn.iocoder.yudao.module.vlog.history.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.vlog.history.dal.dataobject.VLogBrowseHistoryDO;
import cn.iocoder.yudao.module.vlog.history.dal.mysql.VLogBrowseHistoryMapper;
import cn.iocoder.yudao.module.vlog.history.vo.VLogBrowseHistoryPageReqVO;
import cn.iocoder.yudao.module.vlog.info.dal.mysql.VLogInfoMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;

/**
 * 视频浏览记录 Service 实现类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Service
@Validated
public class VLogBrowseHistoryServiceImpl implements VLogBrowseHistoryService {
    private static final int USER_STORE_MAXIMUM = 100;

    @Resource
    private VLogBrowseHistoryMapper browseHistoryMapper;
    @Resource
    private VLogInfoMapper infoMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createBrowseHistory(Long userId, Long vlogId) {
        // 用户未登录时不记录
        if (userId == null) {
            return;
        }
        // 情况一：同一个视频，只保留最新的一条记录
        VLogBrowseHistoryDO history = browseHistoryMapper.selectOneByUserIdAndVlogId(userId, vlogId);
        if (history != null) {
            browseHistoryMapper.deleteById(history);
        } else {
            // 情况二：限制每个用户的浏览记录的条数（只查一条最早地记录、记录总数）
            // TODO @疯狂：这里最好先查询一次数量。如果发现超过了，再删除；主要考虑，可能有部分不超过，提前就多了一次 sql 查询了
            Page<VLogBrowseHistoryDO> pageResult = browseHistoryMapper.selectPageByUserIdOrderByCreateTimeAsc(userId, 1, 1);
            if (pageResult.getTotal() >= USER_STORE_MAXIMUM) {
                browseHistoryMapper.deleteById(CollUtil.getFirst(pageResult.getRecords()));
            }
            // 更新浏览数，重复浏览不计数
            infoMapper.updateBrowseCount(vlogId);
        }
        // 插入浏览记录
        VLogBrowseHistoryDO aDo = new VLogBrowseHistoryDO();
        aDo.setUserId(userId);
        aDo.setVlogId(vlogId);
        browseHistoryMapper.insert(aDo);
    }

    @Override
    public void hideUserBrowseHistory(Long userId, Collection<Long> vlogIds) {
        browseHistoryMapper.updateUserDeletedByUserId(userId, vlogIds, true);
    }

    @Override
    public PageResult<VLogBrowseHistoryDO> getBrowseHistoryPage(VLogBrowseHistoryPageReqVO pageReqVO) {
        return browseHistoryMapper.selectPage(pageReqVO);
    }


}
